'use strict';
import LeeEvent from './LeeEvent.js';
import { APPLIFETIMES } from '../constant.js';

class LeeApp {
  static App = App;
  static Event = LeeEvent;
  static plugin = new Proxy({}, {
    get(target, name) {
      if (/^\//.test(name)) {
        return require(`../..${name}`).default;
      }
      return require(`../../plugins/${name}`).default;
    },
  });

  constructor(options = {}) {
    const { plugins = [], lifetimes = {} } = options;
    const config = {}, event = LeeEvent.$globalEvent;
    for (const name of APPLIFETIMES) {
      if (lifetimes[name] === false) continue;
      if (typeof lifetimes[name] === 'function') {
        event.on(`app/${name}`, lifetimes[name]);
      }
      config[name] = function (...args) {
        const app = this;
        event.emit(`app/${name}`, app, ...args);
      };
    }

    // 内置插件
    const corePlugins = [];
    const corePluginsMap = {
      store: true,
      actionsheet: false,
    };
    for (const name in corePluginsMap) {
      if (options[name] === false) continue;
      if (corePluginsMap[name] === false && !options[name]) continue;
      corePlugins.push(
        require(`../plugins/${name}.js`).default(options[name]),
      );
    }

    event.once('app/onLaunch', app => {
      for (const item of corePlugins.concat(plugins)) {
        item.call(event, app);
      }
    }, null, 9999);
    LeeApp.App(config);
  }
}

App = LeeApp;
